/**
 * 资金回流分析器 - 对象中心化版本
 * 检测 A->B->A 或 A->B->C->A 的资金闭环
 */

class LoopAnalyzer extends BaseAnalyzer {
    constructor(caseId, targetSubject = null) {
        super(caseId, targetSubject);
        this.name = '资金回流';
        this.description = '检测资金闭环回流模式';
    }

    async analyze(params = {}) {
        const minAmount = params.minAmount || 10000;
        const timeWindowDays = params.timeWindowDays || 30;

        const accountFilter = this.getBankAccountFilter();

        // 检测 A->B->A 直接回流
        const sql = `
            WITH OutFlow AS (
                SELECT 
                    account_card as account_a,
                    customer_name as name_a,
                    counterparty_card as account_b,
                    counterparty_name as name_b,
                    transaction_amount as amount_out,
                    transaction_time as time_out
                FROM bank_transactions
                WHERE case_id = ?
                    AND debit_credit_flag = '贷'
                    AND ABS(transaction_amount) >= ?
                    ${accountFilter}
            ),
            InFlow AS (
                SELECT 
                    account_card as account_a,
                    counterparty_card as account_b,
                    transaction_amount as amount_in,
                    transaction_time as time_in
                FROM bank_transactions
                WHERE case_id = ?
                    AND debit_credit_flag = '借'
                    ${accountFilter}
            )
            SELECT 
                o.account_a,
                o.name_a,
                o.account_b,
                o.name_b,
                o.amount_out,
                o.time_out,
                i.amount_in,
                i.time_in,
                CAST((julianday(i.time_in) - julianday(o.time_out)) AS REAL) as days_diff
            FROM OutFlow o
            JOIN InFlow i ON o.account_a = i.account_a 
                AND o.account_b = i.account_b
            WHERE i.time_in > o.time_out
                AND (julianday(i.time_in) - julianday(o.time_out)) <= ?
                AND ABS(ABS(i.amount_in) - ABS(o.amount_out)) / ABS(o.amount_out) <= 0.1
            ORDER BY ABS(o.amount_out) DESC
            LIMIT 50
        `;

        const result = await this.runQuery(sql, [
            this.caseId, minAmount,
            this.caseId,
            timeWindowDays
        ]);

        if (!result.success) {
            return this.createResult('loop', this.name, [], '查询失败: ' + result.message, 'danger');
        }

        const data = result.data;
        const summary = data.length > 0
            ? `检测到 ${data.length} 个资金回流闭环`
            : '未检测到资金回流';

        const level = data.length > 5 ? 'danger' : (data.length > 0 ? 'warning' : 'info');

        return this.createResult('loop', this.name, data, summary, level);
    }

    renderResult(data) {
        if (!data || data.length === 0) {
            return '<div class="empty-result" style="padding:40px; text-align:center; color:#999;">✓ 未发现资金回流</div>';
        }

        let html = `
      <div class="result-summary" style="padding:15px; background:#fef0f0; border-left:4px solid #f56c6c; margin-bottom:15px;">
        <strong>🔄 发现 ${data.length} 个资金回流闭环</strong>
        <p style="margin:5px 0 0; font-size:0.9rem;">资金流出后又回流，疑似洗钱或虚假交易</p>
      </div>
      
      <table class="analysis-result-table" style="width:100%; border-collapse:collapse; font-size:0.9rem;">
        <thead style="background:#f5f7fa;">
          <tr>
            <th style="padding:10px; border:1px solid #e0e0e0;">账户A</th>
            <th style="padding:10px; border:1px solid #e0e0e0;">账户B</th>
            <th style="padding:10px; border:1px solid #e0e0e0; text-align:right;">流出金额</th>
            <th style="padding:10px; border:1px solid #e0e0e0; text-align:right;">回流金额</th>
            <th style="padding:10px; border:1px solid #e0e0e0;">间隔(天)</th>
          </tr>
        </thead>
        <tbody>
    `;

        data.forEach((row, index) => {
            const rowStyle = index % 2 === 0 ? 'background:#fafafa;' : '';
            html += `<tr style="${rowStyle}">`;
            html += `<td style="padding:8px; border:1px solid #e0e0e0;">${row.name_a}<br><small style="color:#909399;">${row.account_a}</small></td>`;
            html += `<td style="padding:8px; border:1px solid #e0e0e0;">${row.name_b || '-'}<br><small style="color:#909399;">${row.account_b || '-'}</small></td>`;
            html += `<td style="padding:8px; border:1px solid #e0e0e0; text-align:right; color:#f56c6c; font-weight:bold;">¥${this.formatAmount(row.amount_out)}</td>`;
            html += `<td style="padding:8px; border:1px solid #e0e0e0; text-align:right; color:#67c23a; font-weight:bold;">¥${this.formatAmount(row.amount_in)}</td>`;
            html += `<td style="padding:8px; border:1px solid #e0e0e0;">${row.days_diff.toFixed(1)}</td>`;
            html += '</tr>';
        });

        html += '</tbody></table>';
        return html;
    }
}

window.LoopAnalyzer = LoopAnalyzer;
